import requests
from bs4 import BeautifulSoup
import datetime

today = str(datetime.datetime.now().date())

def price():
    url = 'http://jgjg.sx.gov.cn/shops_nm2.aspx?id=29&page_number=0'

    # 设置重试次数和超时时间
    max_retries = 10
    retry_count = 0
    timeout = 15  # 设置超时时间为15秒

    while retry_count < max_retries:
        product_list = []  # 定义商品信息列表，每次调用函数时都会重新初始化

        try:
            response = requests.get(url, timeout=timeout)
            response.raise_for_status()  # 如果请求返回了不成功的状态码，会抛出异常

            # 处理返回的内容
            html = response.text
            soup = BeautifulSoup(html, 'html.parser')  # html.parser是BeautifulSoup自带的HTML解析器来解析HTML文档
            #print(soup.body.prettify())
            # 找到目标表格行
            target_rows = soup.find_all('tr', {'bgcolor': ['#ffffff', '#f4f5fa'], 'height': '32'})
            market_rows = str([tag.get_text(strip=True) for tag in soup.find_all('b', class_='text_14_20')]).strip('[]').strip("'")

            # 构造格式化内容
            formatted_content = today + ',' + market_rows + "商品价格：\n"

            for row in target_rows:
                cells = row.find_all('td', {'align': 'center', 'class': 'text_9_16'})
                extracted_content = [cell.text.strip() for cell in cells[:4]]
                for i in range(0, len(extracted_content), 4):
                    goods=extracted_content[i]
                    notes=extracted_content[i + 1]
                    price=extracted_content[i + 3]
                    unit=extracted_content[i + 2]
                    product_info = f"{goods}（{notes}）：{price}元/{unit}"
                    formatted_content += product_info + "\n"

                    # 将商品信息添加到商品列表中
                    product_list.append((goods, notes, price, unit))

            # 打印结果
            print(formatted_content)

            return product_list

        except requests.exceptions.Timeout:
            print("请求超时，尝试重新连接...")
        except requests.exceptions.RequestException as e:
            print(f"请求发生异常：{e}")

        retry_count += 1
        print(f"正在尝试第 {retry_count} 次重新连接...")

    if retry_count == max_retries:
        print(f"已达到最大重试次数 {max_retries}，无法获取数据。")

price()